package com.gm.wholesale.module.login.ui

import android.content.Intent
import android.os.Bundle
import android.view.KeyEvent
import com.gm.commonlib.base.baseBean.DataResp
import com.gm.commonlib.base.baseui.baseactivity.BaseWebViewActivity
import com.gm.commonlib.network.BaseHttpObserver
import com.gm.commonlib.util.permission.PermissionUtil
import com.gm.commonlib.util.permission.interfaces.IPermissionCallback
import com.gm.commonlib.views.dialog.loadingDialog.LoadingDialog
import com.gm.commonlib.views.toast.ToastUtil
import com.gm.wholesale.constant.Constant
import com.gm.wholesale.constant.WebPath
import com.gm.wholesale.module.config.ConfigData
import com.gm.wholesale.module.config.bean.ConfigBean
import com.gm.wholesale.module.config.model.ConfigModel
import com.gm.wholesale.module.login.jsfunction.LoginWebViewCallBack
import com.gm.wholesale.module.main.ui.MainActivity
import com.gm.wholesale.module.user.UserDataManger

class LoginActivity : BaseWebViewActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        UserDataManger.newInstance().clear()
        mViewView.clearCache(true)
        setUserAgent(Constant.SONIC_ANDROID_APP)
        loadUrl("https://peach-genie-test.100cbc.com/genie")
        bindCallBackMethod()
    }

    override fun onResume() {
        super.onResume()
        if (MainActivity.mActivity != null) { //防止没有 finish
            MainActivity!!.mActivity?.finish()
            MainActivity.mActivity = null
            System.gc()
        }
    }

    // todo 绑定js回调的类
    private fun bindCallBackMethod() {
        mViewView.addJavascriptInterface(
            LoginWebViewCallBack(this),
            LoginWebViewCallBack.loginViewCallBack
        )
    }

    //todo 跳转到主界面
    fun startMainActivity() {
        startActivity(Intent(this, MainActivity::class.java))
        finish()
    }

    fun loginSuccess() {
        getConfig();
    }

    private fun getConfig() {

        LoadingDialog.newLoadingDialog().show(activity)
        ConfigModel.getConfig(null, object : BaseHttpObserver<DataResp<ConfigBean?>?>() {
            override fun handleResultOkResp(resp: DataResp<ConfigBean?>?) {
                ConfigData.getConfigData().configBean = resp?.data
                startMainActivity()
            }
            override fun onError(error: String) {
                ToastUtil.showToast(error)
                startLoginAct()
                finish()
            }

            override fun onComplete() {
                LoadingDialog.newLoadingDialog().hid()
            }
        })
    }

    private fun startLoginAct() {
        startActivity(Intent(this, LoginActivity::class.java))
        finish()
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        finish()
        return super.onKeyDown(keyCode, event)
    }
}